
package com.booking.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.booking.R;
import com.booking.adapter.PlacesListAdapter;
import com.booking.entity.BarberShopItem;
import com.booking.entity.ListItem;
import com.booking.utils.InterfaceHelper.GPSHelper;

import java.util.ArrayList;
import java.util.List;

public class PlacesFragment extends BasicFragment {
    private PlacesListAdapter mAdapter;
    private GPSHelper mGPSHelper;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_places_list, container,
                false);
        Context context = getActivity().getApplicationContext();

        mAdapter = new PlacesListAdapter(context);
        ListView listView = (ListView) view.findViewById(R.id.list_view);

        listView.setAdapter(mAdapter);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        new PlacesLoader().execute();
    }

    @Override
    public void updateData() {

    }

    @Override
    public FragmentType getFragmentType() {
        return FragmentType.PLACES_LIST;
    }

    private class PlacesLoader extends AsyncTask<Void, Void, List<ListItem>> {

        @Override
        protected List<ListItem> doInBackground(Void... params) {
            List<ListItem> items = new ArrayList<ListItem>();
            for (int i = 0; i < 10; i++) {
                BarberShopItem barberShopItem = new BarberShopItem();
                barberShopItem.setName("Name " + i);
                barberShopItem.setAddress("Address " + i);
                barberShopItem.setTime("Time " + i);
                barberShopItem.setDistance("Distance " + i);
                barberShopItem
                        .setUrl("http://bushwickdaily.com/wp-content/uploads/2013/01/03.jpg");
                items.add(barberShopItem);
            }
            return items;
        }

        @Override
        protected void onPostExecute(List<ListItem> result) {
            super.onPostExecute(result);
            if (result == null || result.isEmpty() || !isResumed()) {
                return;
            }

            mAdapter.setItems(result);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mGPSHelper = (GPSHelper) activity;
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mGPSHelper = null;
    }
}
